<template>
  <el-dialog
    v-model="visible"
    title="智能生成试卷"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="试卷标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入试卷标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考试科目" prop="subject">
            <el-select
              v-model="form.subject"
              placeholder="请选择科目"
              style="width: 100%"
            >
              <el-option label="语文" value="chinese" />
              <el-option label="数学" value="math" />
              <el-option label="英语" value="english" />
              <el-option label="物理" value="physics" />
              <el-option label="化学" value="chemistry" />
              <el-option label="生物" value="biology" />
              <el-option label="历史" value="history" />
              <el-option label="地理" value="geography" />
              <el-option label="政治" value="politics" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用年级" prop="grade">
            <el-select
              v-model="form.grade"
              placeholder="请选择年级"
              style="width: 100%"
            >
              <el-option label="一年级" value="1" />
              <el-option label="二年级" value="2" />
              <el-option label="三年级" value="3" />
              <el-option label="四年级" value="4" />
              <el-option label="五年级" value="5" />
              <el-option label="六年级" value="6" />
              <el-option label="七年级" value="7" />
              <el-option label="八年级" value="8" />
              <el-option label="九年级" value="9" />
              <el-option label="高一" value="10" />
              <el-option label="高二" value="11" />
              <el-option label="高三" value="12" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="总分" prop="total_score">
            <el-input-number
              v-model="form.total_score"
              :min="10"
              :max="200"
              :step="10"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="及格分数" prop="passing_score">
            <el-input-number
              v-model="form.passing_score"
              :min="1"
              :max="form.total_score - 1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="考试时长" prop="duration">
            <el-input-number
              v-model="form.duration"
              :min="30"
              :max="300"
              :step="15"
              style="width: 100%"
            />
            <span style="margin-left: 8px; color: #909399;">分钟</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">智能生成参数</el-divider>

      <el-form-item label="难度分布" prop="difficulty_distribution">
        <el-radio-group v-model="form.difficulty_distribution">
          <el-radio value="easy">简单为主 (6:3:1)</el-radio>
          <el-radio value="balanced">均衡分布 (5:3:2)</el-radio>
          <el-radio value="hard">困难为主 (3:3:4)</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="知识点覆盖" prop="knowledge_coverage">
        <el-slider
          v-model="form.knowledge_coverage"
          :min="30"
          :max="100"
          :step="5"
          show-stops
          show-input
          :show-input-controls="false"
        />
        <div class="param-desc">覆盖当前年级知识点的百分比</div>
      </el-form-item>

      <el-form-item label="重点知识点" prop="key_knowledge_points">
        <el-select
          v-model="form.key_knowledge_points"
          multiple
          filterable
          allow-create
          placeholder="请选择或输入重点知识点"
          style="width: 100%"
        >
          <el-option-group label="数学">
            <el-option label="函数与方程" value="functions" />
            <el-option label="几何证明" value="geometry" />
            <el-option label="概率统计" value="probability" />
            <el-option label="数列" value="sequence" />
            <el-option label="三角函数" value="trigonometry" />
          </el-option-group>
          <el-option-group label="物理">
            <el-option label="力学" value="mechanics" />
            <el-option label="电磁学" value="electromagnetism" />
            <el-option label="热学" value="thermodynamics" />
            <el-option label="光学" value="optics" />
            <el-option label="原子物理" value="atomic_physics" />
          </el-option-group>
          <el-option-group label="化学">
            <el-option label="无机化学" value="inorganic_chemistry" />
            <el-option label="有机化学" value="organic_chemistry" />
            <el-option label="化学方程式" value="chemical_equations" />
            <el-option label="化学实验" value="chemical_experiments" />
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="题型多样性" prop="question_diversity">
            <el-switch v-model="form.question_diversity" />
            <div class="param-desc">是否包含多种题型</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="避免重复" prop="avoid_duplicates">
            <el-switch v-model="form.avoid_duplicates" />
            <div class="param-desc">避免使用近期已考题目</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">题型配置</el-divider>

      <el-form-item label="题型结构" prop="question_structure">
        <el-table :data="form.question_structure" border>
          <el-table-column label="题型" width="120">
            <template #default="{ row }">
              <el-select v-model="row.type" style="width: 100%">
                <el-option label="选择题" value="choice" />
                <el-option label="填空题" value="fill_blank" />
                <el-option label="判断题" value="judgment" />
                <el-option label="简答题" value="short_answer" />
                <el-option label="作文题" value="essay" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.count"
                :min="0"
                :max="50"
                size="small"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="单题分值" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.score"
                :min="1"
                :max="20"
                size="small"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="总分" width="80">
            <template #default="{ row }">
              {{ row.count * row.score }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button
                size="small"
                type="danger"
                @click="removeQuestionType($index)"
                :disabled="form.question_structure.length <= 1"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 12px;">
          <el-button size="small" @click="addQuestionType">添加题型</el-button>
          <span class="total-score-info">
            总分: {{ calculatedTotal }} 分
          </span>
        </div>
      </el-form-item>

      <el-form-item label="AI增强设置" prop="ai_settings">
        <el-card>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="使用AI出题">
                <el-switch v-model="form.ai_settings.use_ai_generation" />
                <div class="param-desc">使用AI生成部分题目</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="智能难度">
                <el-switch v-model="form.ai_settings.smart_difficulty" />
                <div class="param-desc">根据学生水平调整难度</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="AI生成比例">
                <el-slider
                  v-model="form.ai_settings.ai_ratio"
                  :min="0"
                  :max="100"
                  :step="10"
                  show-input
                  :show-input-controls="false"
                  :disabled="!form.ai_settings.use_ai_generation"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="个性化推荐">
                <el-switch v-model="form.ai_settings.personalized" />
                <div class="param-desc">根据班级特点推荐题目</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="handlePreview" :loading="previewLoading">
        预览效果
      </el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        开始生成
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', data: any): void
  (e: 'preview', data: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const loading = ref(false)
const previewLoading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  title: '',
  subject: '',
  grade: '',
  total_score: 100,
  passing_score: 60,
  duration: 120,
  difficulty_distribution: 'balanced',
  knowledge_coverage: 80,
  key_knowledge_points: [],
  question_diversity: true,
  avoid_duplicates: true,
  question_structure: [
    { type: 'choice', count: 20, score: 2 },
    { type: 'fill_blank', count: 10, score: 2 },
    { type: 'short_answer', count: 3, score: 10 }
  ],
  ai_settings: {
    use_ai_generation: false,
    smart_difficulty: false,
    ai_ratio: 30,
    personalized: false
  }
})

const rules = {
  title: [
    { required: true, message: '请输入试卷标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择考试科目', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请选择适用年级', trigger: 'change' }
  ],
  total_score: [
    { required: true, message: '请输入总分', trigger: 'blur' },
    { type: 'number', min: 10, max: 200, message: '总分在 10-200 之间', trigger: 'blur' }
  ],
  difficulty_distribution: [
    { required: true, message: '请选择难度分布', trigger: 'change' }
  ]
}

const calculatedTotal = computed(() => {
  return form.question_structure.reduce((total, item) => {
    return total + (item.count * item.score)
  }, 0)
})

// 监听题型结构变化，自动调整总分
watch(
  () => calculatedTotal.value,
  (newTotal) => {
    if (newTotal > 0) {
      form.total_score = newTotal
      // 自动调整及格分数
      if (form.passing_score >= newTotal) {
        form.passing_score = Math.floor(newTotal * 0.6)
      }
    }
  }
)

const addQuestionType = () => {
  form.question_structure.push({
    type: 'choice',
    count: 5,
    score: 2
  })
}

const removeQuestionType = (index: number) => {
  if (form.question_structure.length > 1) {
    form.question_structure.splice(index, 1)
  }
}

const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(form, {
    title: '',
    subject: '',
    grade: '',
    total_score: 100,
    passing_score: 60,
    duration: 120,
    difficulty_distribution: 'balanced',
    knowledge_coverage: 80,
    key_knowledge_points: [],
    question_diversity: true,
    avoid_duplicates: true,
    question_structure: [
      { type: 'choice', count: 20, score: 2 },
      { type: 'fill_blank', count: 10, score: 2 },
      { type: 'short_answer', count: 3, score: 10 }
    ],
    ai_settings: {
      use_ai_generation: false,
      smart_difficulty: false,
      ai_ratio: 30,
      personalized: false
    }
  })
  formRef.value?.clearValidate()
}

const handlePreview = async () => {
  try {
    await formRef.value.validate()

    if (calculatedTotal.value === 0) {
      ElMessage.warning('请至少配置一个题型')
      return
    }

    previewLoading.value = true

    // TODO: 调用API预览生成效果
    // const response = await examPaperApi.previewGeneratedPaper(form)

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))

    emit('preview', { ...form })
    ElMessage.success('预览生成成功')
  } catch (error) {
    console.error('预览生成失败:', error)
    ElMessage.error('预览生成失败')
  } finally {
    previewLoading.value = false
  }
}

const handleConfirm = async () => {
  try {
    await formRef.value.validate()

    if (calculatedTotal.value === 0) {
      ElMessage.warning('请至少配置一个题型')
      return
    }

    loading.value = true

    // TODO: 调用API生成试卷
    // const response = await examPaperApi.generatePaper(form)

    // 模拟API调用 - 生成试卷可能需要较长时间
    await new Promise(resolve => setTimeout(resolve, 3000))

    ElMessage.success('试卷生成成功')
    emit('success', { ...form })
    handleClose()
  } catch (error) {
    console.error('生成试卷失败:', error)
    ElMessage.error('生成试卷失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.param-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.total-score-info {
  margin-left: 12px;
  color: #409eff;
  font-weight: 500;
}

:deep(.el-divider__text) {
  background-color: #f5f5f5;
}

:deep(.el-table) {
  .el-input-number {
    .el-input__inner {
      text-align: center;
    }
  }
}

:deep(.el-slider__runway) {
  margin: 16px 0;
}
</style>